<?php

namespace app\business\controller;

use app\business\model\SitesInfoModel;
use app\business\model\SitesModel;
use cmf\controller\AdminBaseController;

class SitesController extends AdminBaseController
{
    /**
     * 站点统计列表
     * @adminMenu(
     *     'name'   => '站点统计列表',
     *     'parent' => 'business/LicensePlate/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 100,
     *     'icon'   => '',
     *     'remark' => '站点统计列表',
     *     'param'  => ''
     * )
     */
    function index()
    {
        $sitesModel = new SitesModel();

        $lists = $sitesModel
            ->paginate();

        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /**
     * 站点统计列表更新
     * @adminMenu(
     *     'name'   => '站点统计列表更新',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 100,
     *     'icon'   => '',
     *     'remark' => '站点统计列表更新',
     *     'param'  => ''
     * )
     */
    function update()
    {
        vendor('baidu/LoginService');
        $loginService = new \LoginService(config('LOGIN_URL'), config('UUID'));
        $ret = $loginService->doLogin(config('USERNAME'), config('PASSWORD'), config('TOKEN'), config('API_URL'));
        if ($ret) {
            $reportService = $loginService->getReportService();
            $ret = $reportService->getSiteList();
            if ($ret['body']['data'][0]['list']) {
                $sitesModel = new SitesModel();
                $arr = [];
                foreach ($ret['body']['data'][0]['list'] as $list) {
                    $site = $sitesModel->where(['site_id' => $list['site_id']])->find();
                    if (!$site) {
                        $arr[] = $list;
                    }
                }
                if ($arr) {
                    $sitesModel->allowField(true)->saveAll($arr);
                }
            }
            $this->success('更新成功！');
        } else {
            $this->error('api接口错误');
        }
    }

    /**
     * 站点访问列表
     * @adminMenu(
     *     'name'   => '站点访问列表',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 100,
     *     'icon'   => '',
     *     'remark' => '站点访问列表',
     *     'param'  => ''
     * )
     */
    function site_info()
    {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->error('非法访问');
        }
        $sitesInfoModel = new SitesInfoModel();

        $lists = $sitesInfoModel
            ->where([
                'site_id' => $id
            ])
            ->order('id desc')
            ->paginate();

        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('page', $page);
        return $this->fetch();
    }

}